package match

import (
	"context"
	"fmt"
	"gitverse.ru/synapse/kubelatte/pkg/api/common"
	"gitverse.ru/synapse/kubelatte/pkg/api/v1alpha1"
	"k8s.io/api/admission/v1beta1"
	"regexp"
)

func existsStringInSlice(rules []string, s string) bool {
	for _, rule := range rules {
		if s == rule || rule == "*" {
			return true
		}
	}
	return false
}

func checkStringsMatchingWithSliceRegexp(rule []string, comparedVal string) bool {
	for _, r := range rule {
		if r == "*" {
			return true
		}

		match, err := regexp.Match(r, []byte(comparedVal))
		if err != nil {
			continue
		}
		if match {
			return true
		}
	}
	return false
}

func doesMatchExpressionsMatch(searchData map[string]string, matchExp []v1alpha1.MatchExpression) bool {
	for _, ex := range matchExp {
		switch selOperator(ex.Operator) {
		case In:
			if in(ex, searchData) {
				return true
			}
		case NotIn:
			if !in(ex, searchData) {
				return true
			}
		case Exists:
			if exists(ex, searchData) {
				return true
			}
		case DoesNotExist:
			if !exists(ex, searchData) {
				return true
			}
		}
	}

	return false
}

func in(exp v1alpha1.MatchExpression, searchData map[string]string) bool {
	val, ok := searchData[exp.Key]
	if !ok {
		return false
	}

	for _, v := range exp.Values {
		if v == val {
			return true
		}
	}
	return false
}

func exists(exp v1alpha1.MatchExpression, searchData map[string]string) bool {
	_, ok := searchData[exp.Key]
	return ok
}

func isNamespaced(ar common.ARFields) bool {
	return ar.Namespace != ""
}

func IsMustProcess(ctx context.Context, data common.ARFields, match v1alpha1.Match) bool {
	if data.Operation == v1beta1.Delete {
		return false
	}
	return CheckMatching(ctx, data, match)
}

func parseMapValuesToString(mapInterface map[string]interface{}) map[string]string {
	var mapString = make(map[string]string)
	for key, value := range mapInterface {
		strValue := fmt.Sprintf("%v", value)
		mapString[key] = strValue
	}
	return mapString
}
